package com.module.base.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;

/**
 * @author bsnl_yanxuwen
 * @date 2020/4/10 10:31
 * Description :
 * 深复制对象
 */
public class CopyUtils {
    /**
     * 需要Serializable
     */
    public static List deepcopy(List list) {
        try {
            ByteArrayOutputStream byteout = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(byteout);
            out.writeObject(list);
            ByteArrayInputStream bytein = new ByteArrayInputStream(byteout
                .toByteArray());
            ObjectInputStream in = new ObjectInputStream(bytein);
            List dest = (List) in.readObject();
            return dest;
        } catch (Exception e) {
            return null;
        }
    }

    public static Object deepcopy(Object obj) throws Exception {
        //将对象写入流
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream oo = new ObjectOutputStream(bo);
        oo.writeObject(obj);
        //从流中读取对象
        ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
        ObjectInputStream bis = new ObjectInputStream(bi);
        return bis.readObject();
    }
}
